package com.atguigu.threadtest;

import java.util.concurrent.locks.ReentrantLock;

/**
 * ClassName: SaleTicket
 * Package: com.atguigu
 * Description:
 *
 * @author: fu-wang
 * @create: 2024/10/28 13:20
 * version: 1.0
 */
public class Ticket{
    private Integer number = 20;
    //ReentrantLock可重入锁
    private final ReentrantLock reentrantLock =  new ReentrantLock(true);//true 开启公平锁
    public void sale(){
        //上锁
        reentrantLock.lock();
        if (number<=0){
            System.out.println("票已售罄");
            //关锁操作必须有
            reentrantLock.unlock();
            return;
        }
        try {
            System.out.println(Thread.currentThread().getName() + "开始售票，当前票数：" + number);
            Thread.sleep(200);
            System.out.println(Thread.currentThread().getName() + "买票售票，剩余票数：" + --number);

            check();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //关锁
            reentrantLock.unlock();
        }

    }
    //测试重入
    public void check(){
        reentrantLock.lock();
        System.out.println("测试重入...,现存余票..."+number);
        reentrantLock.unlock();
    }
}

class Test{
    public static void main(String[] args) {

        Ticket ticket = new Ticket();
        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                ticket.sale();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                ticket.sale();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                ticket.sale();
            }
        }, "C").start();
    }
}